<template>
	<view class="class-list">
		<!-- !classList.length:首次进入时显示 -->
		<!-- !noData:id错误导致的首次进入，请求返回的是空数据 -->
		<view class="loadingLayout" v-if="!classList.length && !noData">
			<uni-load-more status="loading"></uni-load-more>
		</view>

		<view class="content">
			<navigator :url="'/pages/preview/preview?id='+item._id" class="item" v-for="item in classList"
				:key="item._id">
				<image :src="item.smallPicurl" mode="aspectFill"></image>
			</navigator>
		</view>

		<view class="loadingLayout" v-if="classList.length || noData">
			<uni-load-more :status="noData?'noMore':'loading'"></uni-load-more>
		</view>

		<!-- 占位盒：手机底部有虚拟控件，这会挡住样式 -->
		<view class="safe-area-inset-bottom"></view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onUnload,
		onReachBottom,
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app"
	import {
		apiGetClassList,
		apiGetHistoryList
	} from "@/api/api.js"


	const classList = ref([]);
	// 是否有数据；如果请求返回的数据小于我要的说明这次请求后没有数据了，
	// 为了避免重复的无效请求设为true并在 onReachBottom() 中判断
	let noData = ref(false);
	//获取分类列表网络数据
	const getClassList = async () => {
		let res;
		if (queryParams.classid) res = await apiGetClassList(queryParams);
		if (queryParams.type) res = await apiGetHistoryList(queryParams);
		classList.value = [...classList.value, ...res.data];

		// 将图片保存到缓存，预览时直接取出即可
		uni.setStorageSync("storeClassList", classList.value);
		if (queryParams.pageSize > res.data.length) noData.value = true;
	}

	//定义data参数
	const queryParams = {
		pageNum: 1,
		pageSize: 12
	}
	onLoad((e) => {
		let {
			id = null, name = null, type = null
		} = e;
		console.log(e);
		// 用户中心传过来的，download/score
		if (type) queryParams.type = type;
		if (id) queryParams.classid = id;
		pageName = name; // 用于分享时传递
		//修改导航标题
		uni.setNavigationBarTitle({
			title: name
		})
		//执行获取分类列表方法
		getClassList();
	})

	onReachBottom(() => {
		if (noData.value) return;
		queryParams.pageNum++;
		getClassList();
	})


	let pageName;
	//分享给好友
	onShareAppMessage((e) => {
		console.log('share');
		return {
			title: "咸虾米壁纸-" + pageName,
			path: "/pages/class-list/class-list?id=" + queryParams.classid + "&name=" + pageName
		}
	})


	//分享朋友圈
	onShareTimeline(() => {
		return {
			title: "咸虾米壁纸-" + pageName,
			query: "id=" + queryParams.classid + "&name=" + pageName
		}
	})
	
	onUnload(()=>{
		uni.removeStorageSync("storeClassList")
	})
</script>

<style lang="scss" scoped>
	.class-list {
		.content {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 5rpx;
			padding: 5rpx;

			.item {
				height: 440rpx;

				image {
					height: 100%;
					width: 100%;
				}
			}
		}
	}
</style>